using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.ProjectWindowCallback; 
using UnityEngine;


namespace XFFSM
{
    public class FSMStateCreator : EndNameEditAction
    {

        static string regex = "^[a-zA-Z][a-zA-Z0-9_]*$";

        public override void Action(int instanceId, string pathName, string resourceFile)
        {
            CreateFSMState(pathName);
        }


        internal static bool CreateFSMState(string pathName,bool errorTip = true) 
        {

            string fileName = Path.GetFileNameWithoutExtension(pathName);
            // 判断文件是否已经存在 如果已经存在则不能创建

            string[] guids = AssetDatabase.FindAssets(fileName);

            foreach (var item in guids)
            {
                string asset_path = AssetDatabase.GUIDToAssetPath(item);
                MonoScript script = AssetDatabase.LoadAssetAtPath<MonoScript>(asset_path);
                if (script == null || script.GetClass() == null) continue;
                if (script.GetClass().Name.Equals(fileName))
                {
                    if (errorTip) 
                    {                        
                        string message = string.Format("脚本名称:{0}已经存在!", fileName);
                        //FSMEditorWindow.ShowNotification(string.Format("脚本名称:{0}已经存在!", fileName));
                        EditorUtility.DisplayDialog("提示", message, "确定");
                    }
                    return false;
                }
            }

            if (!Regex.Match(fileName, regex).Success)
            { 
                EditorUtility.DisplayDialog("提示", string.Format("文件名:{0}不可用!", fileName), "确定");
                return false;
            }

            TextAsset template = AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/Editor/Template/FSMStateTemplate.txt");
            if (template == null)
            {
                // Packages/com.xfkj.xffsm/Editor/Texture/logo_web.png
                template = AssetDatabase.LoadAssetAtPath<TextAsset>("Packages/com.xfkj.xffsm/Editor/Template/FSMStateTemplate.txt");
            }
            string content = template.text;


            content = content.Replace("{0}", fileName);

            FileStream stream = File.Create(pathName);
            stream.Write(Encoding.UTF8.GetBytes(content), 0, content.Length);
            stream.Close();
            //stream.Write()
            AssetDatabase.Refresh();
            AssetDatabase.SaveAssets();
            return true;
        }

    }

}

